package com.zcmob.web.admanagement.vo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import com.zcmob.web.admanagement.util.TestIo;

import brut.androlib.AndrolibException;
import brut.androlib.ApkDecoder;

public class BatchGetPackagename {

    public static void main(String[] args) {
        String rootPath = "D:\\batchapks\\apks2\\tmpapk\\";
        
        TestIo fileUtil = new TestIo();
        for (File apk : new File(rootPath).listFiles()) {
            if (apk.getName().endsWith(".apk")) {
                try {
                    ApkDecoder decoder = new ApkDecoder();
                    String depath = apk.getAbsolutePath().substring(0, apk.getAbsolutePath().length() - 4);
                    decoder.setOutDir(new File(depath));
                    decoder.setApkFile(apk);
                    decoder.decode();
                    
                    String packagename = getPackagename(depath + "\\AndroidManifest.xml");
                    
                    fileUtil.copyFile(apk.getAbsolutePath(), rootPath + packagename + ".apk");
//                    apk.renameTo(new File(rootPath + packagename + ".apk"));
                    
                } catch (AndrolibException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
    }

    private static String getPackagename(String string) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(string));
            String len = null;
            while ((len = br.readLine()) != null) {
                if (len.contains("<manifest") && len.contains("package=\"")) {
                    // 替换manifest的包名
                    String tmp = len.substring(len.indexOf("package=\"") + 9, len.length());
                    String packagename = tmp.substring(0, tmp.indexOf("\""));
                    return packagename;
                }
            }
        } catch (Exception e) {
            
        }    
        return null;
    }
}
